<template>
  <div class="addCamera">
    <el-button v-if="showBtn" @click="handleClick" v-bind="$attrs">
      <slot></slot>
    </el-button>
    <el-dialog class="d1" :title="title" :visible.sync="visible" append-to-body width="850px" @close="onClose">

      <el-form ref="form" v-loading="loading" label-width="100px" size="mini">
        <el-row>
          <el-col :span="form.monitorItems&&form.monitorItems.length>1?6:8">
            <el-form-item label="监测内容：">{{form.monitor}}</el-form-item>
            <el-form-item label="传感器类型：">{{form.sensorType}}</el-form-item>
            <el-form-item label="设备名称：">{{form.name}}</el-form-item>
            <el-form-item label="传感器编号：">{{form.num}}</el-form-item>
          </el-col>
          <template v-for="(item, index) in form.monitorItems">
            <el-col :span="form.monitorItems.length>2?6:8" :key="index">
              <el-form-item :class="getStyle(item.itemValue>item.threshold3?3:item.itemValue>item.threshold2?2:item.itemValue>item.threshold1?1:0)"
                :label="item.itemName+':'">
                {{item.itemValue!= null ? item.itemValue.toFixed(2)+item.itemUnit: ''}}
              </el-form-item>
              <el-form-item v-if="(item.itemValue>item.threshold3?3:item.itemValue>item.threshold2?2:item.itemValue>item.threshold1?1:0)>0"
                :class="getStyle(item.itemValue>item.threshold3?3:item.itemValue>item.threshold2?2:item.itemValue>item.threshold1?1:0)"
                label="告警级别:">
                {{item.itemValue>item.threshold3?3:item.itemValue>item.threshold2?2:item.itemValue>item.threshold1?1:0}}
              </el-form-item>
              <el-form-item v-if="(item.itemValue>item.threshold3?3:item.itemValue>item.threshold2?2:item.itemValue>item.threshold1?1:0)>0"
                label="告警阈值:">
                {{item.itemValue>item.threshold3?item.threshold3:item.itemValue>item.threshold2?item.threshold2:item.threshold1}}
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <div class="chart">
        <line-chart :opention="opentione" height="350px" width="100%" />
      </div>
      <!-- <div class="align-r">
					<el-button
						size="small"
						@click="visible=false"
					>关 闭</el-button>
				</div> -->
    </el-dialog>
  </div>
</template>

<script>
	import LineChart from "@/views/dashboard/commonTemplate";
  import { listBySensorId } from "@/api/page/index";

  export default {
		components: { LineChart },
		props: {
			showBtn: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				loading: false,
				visible: false,
				title: "告警详情",
				form: {},
        opentione:{}
			};
		},
		computed: {

		},
    created() {
    },
		methods: {
      getStyle(level) {
        let ret = "";
        switch (level) {
          case 1:
            ret = "color-blue";
            break;
          case 2:
            ret = "color-yellow";
            break;
          case 3:
            ret = "color-red";
            break;
          case 4:
            ret = "color-grey";
            break;
          default:
            break;
        }
        return ret;
      },
			onClose() {
				this.form = {};
			},
      initChart(){
        var self = this;
        if(this.form.id!=null) {
          var dateRange = self.getDateRange();
          listBySensorId({
            id:this.form.id,
            begin:dateRange[0],
            end:dateRange[1]
          })
            .then(response => {
              var obj = response.data;
              let legendData = [];
              let xAxisData = [];
              let seriesData = [];
              var name = obj.keywords;
              var gridArr = obj.grid;
              var data = {};
              for (let key  in gridArr[0]) {
                  if (key != "time") {
                    legendData.push(name + "_" + key);
                    data[name + "_" + key] = [];
                  }
              }
              for (var j = 0; j < gridArr.length; j++) {
                  var grid = gridArr[j];
                  if(self.checkAllDataIsNull(grid)) {
                    for (let key  in grid) {
                      if (key != "time") {
                        if (self.checkRate(grid[key])) {
                          data[name + "_" + key].push(grid[key]);
                        } else {
                          data[name + "_" + key].push('-');
                        }
                      }
                    }
                    xAxisData.push(grid.time);
                  }
              }
              for (var k = 0; k < legendData.length; k++) {
                  seriesData.push({
                    name: legendData[k],
                    type: "line", //这个是展示数据的类型，是柱状图还是折线图，饼状图
                    // stack: legendData[i], // 平滑曲线是stack不能一样，否则会在值的上面叠加
                    showSymbol: true,
                    symbol: "circle",
                    symbolSize: 4, //设定实心点的大小
                    hoverAnimation: true,
                    animation: true,
                    data: data[legendData[k]]
                  });
                }
              self.opentione = {
                grid: {
                  top: "30%",
                  bottom: "28px",
                  left: "32px",
                  right: "40px"
                },
                title: {
                  text: this.form.name,
                  x: "left",
                  y: 10,
                  textAlign: "left"
                },
                legend: {
                  orient: "horizontal", //显示方向horizontal横向，vertical纵向
                  x: "center", // 'center' | 'left' | {number}, 横向位置
                  y: 40, // 'center' | 'bottom' | {number}, 纵向位置
                  backgroundColor: "rgb(255, 255, 255)", // 背景颜色
                  borderColor: "rgba(255, 255, 255, 0.8)", // 边框颜色
                  borderWidth: 0, //边框
                  data: legendData
                },
                dataZoom: [{
                  type: 'slider',
                  xAxisIndex: 0,
                  filterMode: 'empty',
                  start: 90,
                  end: 100,
                  lineHeight: 10,
                  // handleSize:5,
                  bottom: 0,
                  textStyle:{
                    lineHeight: 100,
                    fontWeight:"bold",
                    color:"red"
                  }
                }],
                toolbox: {
                  show: true,
                  right: '50px',
                  // 要显示的工具箱内容
                  feature: {
                    saveAsImage: { //保存为图片
                      show: true
                    },
                    magicType: { //动态类型切换
                      type: ['bar', 'line']
                    }
                  }
                },
                tooltip: {
                  trigger: "axis",
                  axisPointer: {
                    // 坐标轴指示器，坐标轴触发有效
                    type: "line" // 默认为直线，可选为：'line' | 'shadow'
                  }
                },
                xAxis: {
                  type: "category",
                  boundaryGap: false,
                  axisTick: {
                    // 是否显示刻度
                    show: false
                  },
                  data: xAxisData,
                  axisLine: {
                    lineStyle: {
                      type: "solid"
                      // color: 'rgb(235, 238, 245)',
                    }
                  }
                },
                yAxis: {
                  name: "mm", // 给y轴加单位
                  type: "value",
                  boundaryGap: false,
                  axisTick: {
                    // 是否显示刻度
                    show: false,
                    default: false
                  },
                  axisLine: {
                    // 是否显示坐标轴对x,y轴有效
                    show: false
                  },
                  splitNumber: 9, // 有多少个刻度
                  splitLine: {
                    show: true,
                    lineStyle: {
                      type: "dashed"
                    }
                  }
                },
                calculable: true,
                series: seriesData
              };
            })
            .catch(err => {
              self.loading = false;
            });
        }
      },
      checkAllDataIsNull(grid){
        var flag = false;
        for (let key  in grid) {
          if (key != "time") {
            if(this.checkRate(grid[key])) {
              flag = true;
            }
          }
        }
        return flag;
      },
      checkRate(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if(regPos.test(val) || regNeg.test(val)) {
          return true;
        } else {
          return false;
        }
      },
			async showDialog(id,level,monitor,monitorItems,name,num,poposition,popopFlag,popsition,postr,sensorType,time,type) {
				this.form = { id,level,monitor,monitorItems,name,num,poposition,popopFlag,popsition,postr,sensorType,time,type } || {};
				this.visible = true;
        this.initChart();
			},
      getDateRange(){
        //昨天的时间
        var day1 = new Date();
        day1.setTime(day1.getTime()-72*60*60*1000);
        var s1 = day1.getFullYear()+"-" + (day1.getMonth()+1) + "-" + day1.getDate();
        //今天的时间
        var day2 = new Date();
        day2.setTime(day2.getTime());
        var s2 = day2.getFullYear()+"-" + (day2.getMonth()+1) + "-" + day2.getDate();
        return [s1,s2];
      }
		}
	};
</script>
<style>
  .color-grey {
    color: black!important;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom: 6px;
  }
</style>
